import React, {FC, useEffect, useMemo, useState} from 'react'
import {useLocation} from 'umi'
import {Modal, Table, Pagination} from 'antd'
import SearchForm from '@/components/SearchForm'
import {getCars, getOutCarPage, saveCar} from '@/service/customer/fleet'
import {getDriverbyCarId} from '@/service/customer/driver'

interface AddVehicleInfoType {
	addModalVisivle: boolean
	setAddModalVisivle: (visible: boolean) => void
	callBack?: () => void
	idArr: any[]
	dict: any
}

// const carStatus: any = {
// 	1: '待验车入库',
// 	2: '待备车',
// 	3: '拒收',
// 	4: '可排车',
// 	7: '可发车',
// 	8: '用车中',
// 	9: '停运',
// 	10: '退出运营',
// }

const addVehicleInfoModal: FC<AddVehicleInfoType> = ({
	addModalVisivle,
	setAddModalVisivle,
	callBack,
	idArr,
	dict,
}) => {
	const loaction: any = useLocation()
	const [saveLoading, setSaveLoading] = useState(false)
	const [loading, setLoading] = useState(false)
	const [pagination, setPagination] = useState({
		current: 1,
		size: 10,
	})
	const [total, setTotal] = useState(0)
	const [selectedRow, setSelectedRow] = useState<any[]>([])

	const feetId = useMemo(() => loaction?.query?.id, [loaction])
	const FleetFormItems: any[] = [
		{
			type: 'group',
			key: 'group1',
			groupItems: [
				{
					type: 'select',
					key: 'carStatus',
					name: 'carStatus',
					label: '车辆状态',
					keys: 'dictKey',
					title: 'dictValue',
					items: dict?.carStatus,
				},
				{
					type: 'input',
					key: 'carId',
					name: 'carId',
					label: '车辆id',
					rules: [
						{
							pattern: /^[0-9]*$/,
							message: '车辆id请输入数字',
						},
					],
				},
				{
					type: 'input',
					key: 'number',
					name: 'number',
					label: '车牌号',
				},
			],
		},
		{
			type: 'group',
			key: 'group2',
			groupItems: [
				{
					type: 'input',
					key: 'carFullName',
					name: 'carFullName',
					label: '品牌车系车型',
				},
				{},
				{},
			],
		},
	]

	const Cloums: any[] = useMemo(
		() => [
			{title: '车辆ID', dataIndex: 'carId', align: 'center'},
			{title: '车牌号', dataIndex: 'number', align: 'center'},
			{title: '品牌车系车型', dataIndex: 'carFullName', align: 'center'},
			{
				title: '车辆状态',
				dataIndex: 'carStatus',
				align: 'center',
				render: (text: any) => (
					<>
						{
							dict?.carStatus.map((res:any)=>{
								if(Number(res.dictKey) === text){
									return <span>{res.dictValue}</span>
								}
								return ''
							})
						}
					</>
					
				)
			},
			{title: '司机姓名', dataIndex: 'name', align: 'center'},
			{title: '司机联系方式', dataIndex: 'tel', align: 'center'},
			{title: '租赁日期', dataIndex: '', align: 'center'},
		],
		[dict?.carStatus],
	)

	const [listData, setListData] = useState([])
	const [formData, setFormData] = useState({})

	const getData = async (params?: any) => {
		const obj = {
			current: 1,
			size: 10,
			...params,
		}
		setLoading(true)
		const res1 = await getCars()
		if (res1.data) {
			const data2 = {
				// idsList: params?.carId || (res1.data || []).join(','),
				idsList: (res1.data || [])
					.filter((item: any) => item !== params?.carId)
					.join(','),
				...obj,
			}
			const res2 = await getOutCarPage(data2)
			if (res2.data.total) {
				setTotal(res2.data.total)
			} else {
				setTotal(0)
			}
			if (res2.data?.records?.length) {
				const list: any = []
				res2.data.records.forEach(async (item: any) => {
					const NewItem = item
					const res3 = await getDriverbyCarId({carId: item.carId})
					if (res3.data) {
						NewItem.driverId = res3.data.driverId
						NewItem.name = res3.data.name
						NewItem.tel = res3.data.tel
					}
					list.push(NewItem)
					if (list.length === res2.data.records.length) {
						setListData(list)
						setTimeout(() => {
							setLoading(false)
						}, 0)
					}
				})
			} else {
				setListData([])
				setLoading(false)
			}
		}
	}

	const paginationChange = (current: number, size: number) => {
		setPagination({
			current,
			size,
		})
		getData({
			...formData,
			current,
			size,
		})
	}
	useEffect(() => {
		if (!addModalVisivle) return
		getData()
		setFormData({})
		setPagination({
			current: 1,
			size: 10,
		})
	}, [addModalVisivle])

	const onSave = async () => {
		setSaveLoading(true)
		saveCar({feetId, carIds: selectedRow.join()})
		try {
			// eslint-disable-next-line no-unused-expressions
			if (typeof callBack === 'function') {
				setTimeout(() => {
					callBack()
				}, 1000)
			}
			setSelectedRow([])
			setSaveLoading(false)
			setAddModalVisivle(false)
		} catch (e) {
			setSaveLoading(false)
		}
	}

	return (
		<Modal
			title="添加车辆"
			open={addModalVisivle}
			onCancel={() => {
				setAddModalVisivle(false)
			}}
			width={1000}
			onOk={onSave}
			okButtonProps={{loading: saveLoading}}
			forceRender>
			{addModalVisivle ? (
				<div className="addVehicleInfo">
					<div className="searchBox">
						<SearchForm
							formLayout={{
								labelCol: {flex: '90px'},
								wrapperCol: {flex: '1'},
							}}
							formItems={FleetFormItems}
							onReset={() => {
								setFormData({})
								getData({})
							}}
							onFinish={(value) => {
								setFormData(value)
								setPagination({
									current: 1,
									size: 10,
								})
								getData(value)
							}}
						/>
					</div>
					<div className="content">
						<div className="select">
							已选择{selectedRow.length || 0}辆车
						</div>
						<Table
							columns={Cloums}
							rowKey="carId"
							dataSource={listData}
							loading={loading}
							rowSelection={{
								type: 'checkbox',
								onChange: (selectedRowKeys: React.Key[]) => {
									setSelectedRow(selectedRowKeys)
								},
								getCheckboxProps: (record: any) => ({
									disabled: idArr.includes(record.carId),
								}),
							}}
							scroll={{x: 1200, y: 400}}
							pagination={false}
						/>
						<div className="pagination">
							<Pagination
								pageSizeOptions={[10, 20]}
								defaultCurrent={1}
								current={Number(pagination.current)}
								total={total ? Number(total) : 0}
								// eslint-disable-next-line no-shadow
								showTotal={(totals, range) =>
									`第  ${range[0]} - ${range[1]} 条 / 总共 ${totals} 条`
								}
								showSizeChanger
								showQuickJumper
								onChange={paginationChange}
							/>
						</div>
					</div>
				</div>
			) : (
				<></>
			)}
		</Modal>
	)
}

export default addVehicleInfoModal
